<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use app\common\model\Express;
use \app\common\model\OrderGoods;
use think\Db;
use Logistics\Logistics;
/**
 * 订单列管理
 *
 * @icon fa fa-circle-o
 */
class Order extends Backend
{
    
    /**
     * Order模型对象
     * @var \app\common\model\Order
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\Order;
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->view->assign("paytype_list", $this->model->getPayTypeList());
    }

    public function import()
    {
        parent::import();
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    

    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                    ->with(['user'])
                    ->where($where)
                    ->order($sort, $order)
                    ->paginate($limit);

            foreach ($list as $row) {
                $row->visible(['id','order_sn','price','actual_price','status','createtime','paytype','paytime','courier_code','tracking_number']);
                $row->visible(['user']);
				$row->getRelation('user')->visible(['username']);
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }
    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $goods_list = OrderGoods::where('order_id',$row['id'])->order('id asc')->select();
        $this->view->assign("row", $row);
        $this->view->assign("goods_list", $goods_list);
        return $this->view->fetch();
    }
    /**
     * 发货
     */
    public function go_ship($ids = "")
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                if($row['status'] != 1){
                    $this->error('只有已付款的订单才能发货');
                }
                $params['courier_company'] = Express::where('express_code',$params['courier_code'])->value('express_name');
                $params['status'] = 2;
                $params['shiptime'] = time();
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $express_list = Express::order('id asc')->select();
        $this->view->assign("express_list", $express_list);
        return $this->view->fetch();
    }
    //操作退款申请
    public function refund($ids = null)
    {
        $row = $this->model->get($ids);
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($row['status'] != 4) {
                $this->error('数据异常');
            } else {
                //确认退款
                if($params['status'] == 5){
                    $result['result_code'] = 'SUCCESS';
                    Db::startTrans();
                    try {
                        //更改订单状态
                        $res = $this->model->where('id', $row['id'])->update(['status' => 5]);
                        if($res && $row['price'] >0.01){
                            //对接退款接口

                        }
                        Db::commit();
                    } catch (ValidateException $e) {
                        Db::rollback();
                        $this->error($e->getMessage());
                    } catch (PDOException $e) {
                        Db::rollback();
                        $this->error($e->getMessage());
                    } catch (Exception $e) {
                        Db::rollback();
                        $this->error($e->getMessage());
                    }
                }else{
                    //驳回退款
                    Db::startTrans();
                    try {
                        $result['result_code'] = 'SUCCESS';
                        if(!$params['reason'] || $params['reason'] == ''){
                            $this->error('请填写驳回原因');
                        }
                        $res = $this->model->where('id', $row['id'])->update(['status' => 6,'reason'=>$params['reason']]);
                        Db::commit();
                    } catch (ValidateException $e) {
                        Db::rollback();
                        $this->error($e->getMessage());
                    } catch (PDOException $e) {
                        Db::rollback();
                        $this->error($e->getMessage());
                    } catch (Exception $e) {
                        Db::rollback();
                        $this->error($e->getMessage());
                    }
                }
                if($res && $result ){
                    //$result = json_decode($result,true);
                    if($result['result_code'] == 'SUCCESS'){
                        $this->success('操作成功');
                    }
                }
                $this->error('操作失败');
            }
        }
        if($row['refund_images']){
            $row['refund_images'] = explode(',',$row['refund_images']);
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }
    /**
     * 查看物流
     */
    public function logistics($ids = null)
    {
        $Logistics = new Logistics();
        $info = $this->model->where(['id' => $ids])->field('id,courier_code,tracking_number')->find();
        if (empty($info)) {
            $this->error(__('No Results were found'));
        }
        if($info['courier_code'] == '' || $info['tracking_number'] == ''){
            $this->error('参数不正确');
        }
        $expressinfo = json_decode($Logistics->getlogistics($info['courier_code'], $info['tracking_number']), true);
        //print_r($expressinfo);exit;
        if(isset($expressinfo['returnCode']) && $expressinfo['returnCode'] != 200){
            $this->error($expressinfo['message']);
        }
        if (!isset($expressinfo['data'])) {
            $expressinfo['data'][] = [
                'time' => date('Y-m-d H:i:s'),
                'status' => '已发货',
                'context' => '包裹正在等待快递小哥揽收~'
            ];
        }
       /* $expressinfo['data'][] = [
            'time' => date('Y-m-d H:i:s'),
            'status' => '已发货',
            'context' => '包裹正在等待快递小哥揽收~'
        ];*/
        $this->assign([
            'expressinfo'     => $expressinfo,
        ]);
        return $this->view->fetch();
    }
}
